/*  
 * Copyright (c) 2015-2026 LeeSon Ltd. All Rights Reserved.  
 * LeeSon  QQ:25901875
 */
package com.leeson.portal.manage.view.action;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.leeson.portal.core.model.Config;
import com.leeson.portal.core.model.OnlineMap;
import com.leeson.portal.core.service.InterfaceControl;
import com.leeson.portal.manage.base.BaseAction;
import com.leeson.portal.manage.domain.Account;
import com.leeson.portal.manage.domain.LinkRecord;
import com.leeson.portal.manage.domain.LogRecord;
import com.leeson.portal.manage.domain.PageBean;

@Controller
@Scope("prototype")
public class LinkRecordAction extends BaseAction<LinkRecord> {

	private static final long serialVersionUID = -4296032514753579198L;
	
	Logger logger = Logger.getLogger(LinkRecordAction.class);
	Config cfg = Config.getInstance();
	
    private int pageNum=1;  //当前页
    private int pageSize=10;  //每页多少条记录
	private String[] choose;
	
	public int getPageNum() {
		return pageNum;
	}

	public void setPageNum(int pageNum) {
		this.pageNum = pageNum;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public String[] getChoose() {
		return choose;
	}

	public void setChoose(String[] choose) {
		this.choose = choose;
	}

	/**
	 * 列表（带分页）
	 * 
	 * @return
	 */
	public String list() {
		LinkRecord searchModel = new LinkRecord();
		StringBuffer sb = new StringBuffer("where 1=1 ");
		if(model.getUid()!=null&&!model.getUid().equals("")){
			sb.append(" and uid='"+model.getUid()+"'");
			searchModel.setUid(model.getUid());
		}
		if(model.getId()!=null&&!model.getId().equals("")){
			sb.append(" and id='"+model.getId()+"'");
			searchModel.setId(model.getId());
		}
		if(model.getLoginName()!=null&&!model.getLoginName().equals("")){
			sb.append(" and loginName like '%"+model.getLoginName()+"%' ");
			searchModel.setLoginName(model.getLoginName());
		}
		if(model.getState()!=null&&!model.getState().equals("")){
			sb.append(" and state='"+model.getState()+"'");
			searchModel.setState(model.getState());
		}
		if(model.getIp()!=null&&!model.getIp().equals("")){
			sb.append(" and ip='"+model.getIp()+"'");
			searchModel.setIp(model.getIp());
		}
		
		sb.append(" order by id desc");

		
		PageBean pageBean=linkRecordService.findByConditionWithPage(pageNum,pageSize,sb.toString());
		ActionContext.getContext().getValueStack().push(pageBean);
		ActionContext.getContext().getValueStack().push(searchModel);
		return "list";
	}

	/**
	 * 删除
	 * 
	 * @return
	 */
	public String delete() {
		linkRecordService.delete(model.getId());
		return "toList";
	}

	/**
	 * 删除多选
	 * 
	 * @return
	 */
	public String deleteChoose() {
		if (choose != null && choose.length > 0) {
			for (int i = 0; i < choose.length; i++) {
				linkRecordService.delete(Long.parseLong(choose[i]));
			}
		}
			
		return "toList";
	}
	
	
	/**
	 * 在线列表（带分页）
	 * 
	 * @return
	 * @throws ParseException 
	 */
	public String listOnline() throws ParseException {
		HashMap<String, String[]> onlineUserMap=OnlineMap.getInstance().getOnlineUserMap();
		LinkRecord searchModel = new LinkRecord();
		List<LinkRecord> onlineList=new ArrayList<LinkRecord>();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss"); 
		
		Iterator<String> iterator = onlineUserMap.keySet().iterator();
		while (iterator.hasNext()) {
			Object o = iterator.next();
			String host = o.toString();
			String[] loginInfo = onlineUserMap.get(host);
			String username = loginInfo[0];
			String time =loginInfo[3];
			Date loginTime=format.parse(time);
			
			Boolean state=true;
			if(model.getIp()!=null&&!model.getIp().equals("")){
				searchModel.setIp(model.getIp());
				if(!model.getIp().equals(host)){
					state=false;
				}
			}
			if(model.getLoginName()!=null&&!model.getLoginName().equals("")){
				searchModel.setLoginName(model.getLoginName());
				if(!model.getLoginName().equals(username)){
					state=false;
				}
			}
			
			if(state){
				LinkRecord lr=new LinkRecord();
				lr.setId(Long.parseLong((String.valueOf(onlineList.size()+1))));
				String nowString=format.format(new Date());
				Date nowTime=format.parse(nowString);
				Long costTime=nowTime.getTime()-loginTime.getTime();
				lr.setTime(costTime);
				Account accTemp=accountService.findByCondition("where loginName = '"+username+"' ").get(0);
				lr.setState(accTemp.getState());
				lr.setUid(accTemp.getId());
				lr.setLoginName(username);
				lr.setIp(host);
				lr.setStartDate(loginTime);
				onlineList.add(lr);
			}
			
		}
		
		PageBean pageBean=new PageBean(this.pageNum, this.pageSize, onlineList.size(), onlineList);
//				linkRecordService.findByConditionWithPage(pageNum,pageSize,"条件");
		ActionContext.getContext().getValueStack().push(pageBean);
		ActionContext.getContext().getValueStack().push(searchModel);
		return "listOnline";
	}
	
	
	/**
	 * 下线
	 * 
	 * @return
	 */
	public String kick() {
		
		kickMethod(model.getIp());
		
		return "toListOnline";
	}

	
	/**
	 * 下线多选
	 * 
	 * @return
	 */
	public String kickChoose() {
		if (choose != null && choose.length > 0) {
			for (int i = 0; i < choose.length; i++) {
				kickMethod(choose[i]);
			}
		}
			
		return "toListOnline";
	}
	
	
//-----------------------------------------------------------------------------------------------------	
	
	/**
	 * 下线操作方法
	 * @param ip
	 */
	private void kickMethod(String ip) {
		OnlineMap onlineMap=OnlineMap.getInstance();
		HashMap<String, String[]> onlineUserMap=OnlineMap.getInstance().getOnlineUserMap();
		boolean state=onlineUserMap.containsKey(ip);
		if (state) {
			String[] loginInfo = onlineUserMap.get(ip);
			String username = loginInfo[0];
		
			Boolean info = InterfaceControl.Method("PORTAL_LOGINOUT",
					username, username, ip);

			if (info == true) {
				
				//改变连接日志，修改计费记录
				if(cfg.getAuth_interface().equals("1")){
					doLinkRecord(ip,loginInfo);
				}
				
				//修改在线列表
				onlineMap.getOnlineUserMap().remove(ip);
				
				//新建下线日志
				doLogRecord(ip, username);
			}
		}
	}
	/**
	 * 下线日志
	 * @param request
	 * @param ip
	 * @param username
	 */
	private void doLogRecord(String ip,
			String username) {
		LogRecord logRecord=new LogRecord();
		Date nowDate=new Date();
		logRecord.setInfo("IP:"+ip+",用户："+username+",被管理员踢下线！");
		logRecord.setRec_date(nowDate);
		logRecordService.save(logRecord);
	}
	/**
	 * 连接日志
	 * @param request
	 * @param ip
	 * @param username
	 */
	private void doLinkRecord(String ip,String[] loginInfo) {
		
		Long userId=Long.parseLong(loginInfo[1]);
		Long recordId=Long.parseLong(loginInfo[2]);
		Date now=new Date();
		
		LinkRecord linkRecord=linkRecordService.getById(recordId);
		linkRecord.setEndDate(now);
		Long costTime=now.getTime()-linkRecord.getStartDate().getTime();
		linkRecord.setTime(costTime);
		linkRecordService.update(linkRecord);
		
		Account account=accountService.getById(userId);
		String state=account.getState();
		Long haveTime=account.getTime();
		Long newHaveTime=haveTime-costTime;
		if(state.equals(String.valueOf(2))){
			if(newHaveTime<=0){
				account.setState(String.valueOf(0));
			}
			account.setTime(newHaveTime);
			accountService.update(account);
		}
		
	}
	
}
